﻿
@{
    ViewBag.Title = "OneToOneChat";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>会议室</title>
    <meta charset="utf-8" />
    <style>
        div.chat-window {
            width: 500px;
            border: 2px solid #007acc;
            margin: 5px 0;
            padding: 5px;
        }
    </style>
</head>

<body>
    <h2>个人聊天</h2>

    <div>
        <div>用户名称：【<strong id="userName"></strong>】</div>
        <div>当前连接Id:【<span id="connId"></span>】</div>
    </div>
    <div>
        <h4>在线用户列表：</h4>
        <ul id="onlineUser"></ul>
    </div>
    <div id="discussion">

    </div>


    <script src="~/Scripts/jquery-3.5.0.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.4.1.min.js"></script>
    @*<script src="Scripts/jquery.signalR-2.4.1.min.js"></script>*@
    <!--动态生成的一个js文件，由SignaIR生成的脚本文件-->>
    <script src="~/signalr/hubs"></script>
    <script>
        //当前用户对象
        const currentUser = {
            name: '',
            connectionId: ''
        };

        //代理集线器，表示服务端
        var chat;
        $(function () {
            //创建服务端chat的代理
            chat = $.connection.chat;
            registerClientWork();
            bindChat();
            bindMessageSend();

            currentUser.name = window.prompt('enter your name:');
            $('#userName').text(currentUser.name)

            //done()建立连接完成的回调
            $.connection.hub.start().done(function () {
                currentUser.connectionId = $.connection.hub.id;
                $('#connId').text(currentUser.connectionId);
                //调用服务端Hub中UpdateUserName,RPC调用
                chat.server.updateUserName(currentUser.name);
            });
        })

        //在代理chat上注册客户端的行为，供服务器进行RPC调用
        function registerClientWork() {
            //定义客户端的更新在线用户列表方法，方便Hub进行RPC调用
            chat.client.updateOnlineUser = function (data) {
                //debugger;
                let userArray = JSON.parse(data);
                if (userArray.length > 0) {
                    $('#onlineUser').empty();
                    for (let uu of userArray) {
                        let chatButton = '';
                        if (uu.ConnectionId != currentUser.connectionId) {
                            chatButton = `<button class="chat-button"
                                    data-connid="${uu.ConnectionId}"
                                    data-name="${uu.Name}">聊天</button>`;
                        }
                        $('#onlineUser').append(`<li>用户名：【${uu.Name}${chatButton}】</li>`);
                    }
                }
            }
            //定义消息发送的方式，Hub中进行调用
            chat.client.addMessage = function (message, targetName, targetConnId) {
                console.log(`【接收到服务端消息】您的聊天人：${targetName},对方Id是：${targetConnId}`);
                if ($(`#${targetConnId}`).length == 0) {
                    showChatWindow(targetConnId, targetName);
                }
                $(`#${targetConnId}`).find('ul.chat-content').append(`<li>${message}</li>`);
            }
        }

        //委托方式绑定聊天事件
        function bindChat() {
            $('#onlineUser').on('click', 'button.chat-button', function (e) {
                let targetConnId = $(e.target).attr('data-connid');
                let targetName = $(e.target).attr('data-name');

                showChatWindow(targetConnId, targetName);
            });
        }

        //委托方式绑定发送消息事件
        function bindMessageSend() {
            $("#discussion").on('click', 'button.btn-send', function (e) {
                let targetConnId = $(e.target).attr('data-connid');
                let message = $(e.target).prev().val();
                message = `${currentUser.name}:${message}`;
                console.log(`【发送消息】消息内容：${message},聊天者id为：${targetConnId}`);

                //调用服务端SendMessage方法
                chat.server.sendMessage(targetConnId, message);
                $(e.target).prev().val('');
            });
        }

        //显示聊天窗口
        function showChatWindow(connid, uname) {
            let html = `
                    <div class ="chat-window" id="${connid}">
                    <div><span>正在与【${uname}】聊天中...</span></div>
                    <ul class ="chat-content"></ul>
                    <div>
                    <input type="text"/>
                    <button class ="btn-send" data-connid="${connid}">send</button>
                    </div>
                    </div>
                    `;
            $('#discussion').append(html);
        }
    </script>
</body>
</html>
